package cn.liontalk.controller;

import cn.liontalk.annotation.AccessLimit;
import cn.liontalk.common.redis.RedisService;
import cn.liontalk.common.redis.prefix.GoodsKey;
import cn.liontalk.common.redis.prefix.MiaoShaKey;
import cn.liontalk.common.result.Result;
import cn.liontalk.entity.User;
import cn.liontalk.service.GoodsService;
import cn.liontalk.service.UserService;
import cn.liontalk.service.impl.UserServiceImpl;
import cn.liontalk.vo.GoodsDetailVO;
import cn.liontalk.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Locale;

/**
 * @author: 周哲
 * @package: cn.liontalk.controller
 * @description:
 * @date: 2019/1/20 11:44
 * @version: V1.0
 */
@Controller
@RequestMapping(value = "/goods")
public class GoodsController {


    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;


    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    @Autowired
    RedisService redisService;





   /* @RequestMapping(value = "/index")
    public String getGoodListIndex(HttpServletResponse response,Model model, @CookieValue(value = UserServiceImpl.COOK_NAME_TOKEN,required = false) String cookieToken,
                                   @RequestParam(value = UserServiceImpl.COOK_NAME_TOKEN,required = false) String paramToken){
        if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)){
            return "login";
        }
        String token = !StringUtils.isEmpty(cookieToken) ? cookieToken : paramToken;
        User user  = userService.getUserByToken(response,token);
        model.addAttribute("user",user);
        return "goods_list";
    }*/


    /**
     * 没有优化之前
     * QPS : 143.2
     * 2500 * 10
     *
     * @param user
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", produces = "text/html")
    @ResponseBody
    public String getGoodListIndex(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("user", user);
        String html = redisService.get(GoodsKey.goodsList, ":list", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }


        List<GoodsVO> list = goodsService.listGoodsVO();
        model.addAttribute("list", list);
        IWebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);

        //再次缓存起来
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.goodsList, ":list", html);
        }
        return html;

       /* List <GoodsVO> list = goodsService.listGoodsVO();
        model.addAttribute("list", list);
        return "goods_list";*/

    }


    /**
     * 利用页面缓存将 商品详情缓存起来。
     *
     * @param user
     * @param model
     * @param goodsId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/detail/{goodsId}", produces = "text/html")
    @ResponseBody
    public String getGoodsDetail(User user, Model model, @PathVariable("goodsId") Long goodsId,
                                 HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("user", user);

        String html = redisService.get(GoodsKey.goodsDetail, ":detail", String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        GoodsVO goodsVO = goodsService.queryGoodsById(goodsId);
        model.addAttribute("goods", goodsVO);
        long startAt = goodsVO.getStartTime().getTime();
        long endAt = goodsVO.getEndTime().getTime();
        long nowTime = System.currentTimeMillis();
        int secKillStatus = 0;
        int remainSeconds = 0;
        if (startAt > nowTime) {
            //秒杀没有开始
            secKillStatus = 0;
            remainSeconds = (int) (startAt - nowTime) / 1000;
        } else if (endAt < nowTime) {
            //秒杀结束了
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行时
            secKillStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        IWebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.goodsDetail, ":detail", html);
        }
        return html;
    }


    /**
     * 使用前后端分离技术
     *
     * @param goodsId
     * @param user
     * @return
     */
    @RequestMapping(value = "/detach/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVO> getGoodsDetailVOInfo(@PathVariable("goodsId") Long goodsId, User user) {
        GoodsVO goodsVO = goodsService.queryGoodsById(goodsId);
        Integer secKillStatus = 0;
        Integer remainSeconds = 0;
        long startAt = goodsVO.getStartTime().getTime();
        long endAt = goodsVO.getEndTime().getTime();
        long nowTime = System.currentTimeMillis();
        if (startAt > nowTime) {
            //秒杀没有开始
            secKillStatus = 0;
            remainSeconds = (int) (startAt - nowTime) / 1000;
        } else if (endAt < nowTime) {
            //秒杀结束了
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行时
            secKillStatus = 1;
            remainSeconds = 0;
        }
        GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
        boolean result = redisService.keyExist(MiaoShaKey.hasKillThisGoods, "" + user.getId() + "_" + goodsId);
        if (result) {
            goodsDetailVO.setStatus(true);
        } else {
            goodsDetailVO.setStatus(false);
        }
        goodsDetailVO.setGoodsVO(goodsVO);
        goodsDetailVO.setRemainSeconds(remainSeconds);
        goodsDetailVO.setSecKillStatus(secKillStatus);
        goodsDetailVO.setUser(user);
        return Result.success(goodsDetailVO);
    }

}
